package com.groupbuying.customerconsumer.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.groupbuying.customerconsumer.connector.SysconfigFeign;
import com.groupbuying.customerconsumer.constants.CommonConstants;
import com.groupbuying.customerconsumer.constants.CustomerAliinfoRelEnumConstants;
import com.groupbuying.customerconsumer.constants.CustomerAliinfoRelSearchConstants;
import com.groupbuying.customerconsumer.constants.CustomerAlipayConstants;
import com.groupbuying.customerconsumer.dao.CustomerAliinfoRelDao;
import com.groupbuying.customerconsumer.dao.CustomerUshopDao;
import com.groupbuying.customerconsumer.domain.CustomerAliinfoRelDO;
import com.groupbuying.customerconsumer.domain.CustomerUshopDO;
import com.groupbuying.customerconsumer.domain.UserToken;
import com.groupbuying.customerconsumer.service.CustomerAliinfoRelService;
import com.groupbuying.customerconsumer.utils.AliUntil;
import com.groupbuying.customerconsumer.utils.JwtUtils;
import com.groupbuying.customerconsumer.utils.apiresult.ApiResult;
import com.groupbuying.customerconsumer.utils.apiresult.ApiResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CustomerAliinfoRelServiceImpl implements CustomerAliinfoRelService {
	private static final Logger logger = LoggerFactory.getLogger(CustomerAliinfoRelServiceImpl.class);
	@Autowired
	private CustomerAliinfoRelDao customerAliinfoRelDao;
	@Autowired
	private SysconfigFeign sysconfigFeign;
	@Autowired
	CustomerUshopDao customerUshopDao;
	@Override
	public CustomerAliinfoRelDO get(String customerId){
		return customerAliinfoRelDao.get(customerId);
	}
	
	@Override
	public List<CustomerAliinfoRelDO> list(Map<String, Object> map){
		return customerAliinfoRelDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return customerAliinfoRelDao.count(map);
	}
	
	@Override
	public int save(CustomerAliinfoRelDO customerAliinfoRel){
		return customerAliinfoRelDao.save(customerAliinfoRel);
	}
	
	@Override
	public int update(CustomerAliinfoRelDO customerAliinfoRel){
		return customerAliinfoRelDao.update(customerAliinfoRel);
	}
	
	@Override
	public int remove(String customerId){
		return customerAliinfoRelDao.remove(customerId);
	}
	
	@Override
	public int batchRemove(String[] customerIds){
		return customerAliinfoRelDao.batchRemove(customerIds);
	}

	@Override
	public ApiResult customerAliRegister(String authCode) {
		try{
			Map<String, String> param = sysconfigFeign.getByAppliName(CustomerAlipayConstants.APPLICATIONNAME);
			AlipaySystemOauthTokenResponse response = AliUntil.getAccessToken(authCode,param);
			if(response.getCode()!=null){
				return ApiResult.failure("获取access_token 和 user_id失败");
			}
			//获取accesstoken
			String accessToken = response.getAccessToken();
			//获取aliPayUserId
			String aliPayUserId = response.getUserId();
			logger.info("accessToken为:{}，aliPayUserId为:{}",accessToken,aliPayUserId);
			Map<String,Object> parma = new HashMap<>();
			parma.put(CustomerAliinfoRelSearchConstants.SEARCH_ALIPAYUSERID,aliPayUserId);
			List<CustomerAliinfoRelDO> customerAliinfoRelDOS = customerAliinfoRelDao.list(parma);
			CustomerUshopDO customerUshopDO = new CustomerUshopDO();
			if(customerAliinfoRelDOS==null|| customerAliinfoRelDOS.size()==0){
				//创建子平台账户
				customerUshopDO.setCustomerId(sysconfigFeign.getCustomerID());
				customerUshopDO.setGmtCreate(new Date());
				customerUshopDO.setGmtModified(new Date());
				customerUshopDO.setIsDelete(CustomerAliinfoRelEnumConstants.ENUM_ISDELETE_UNDEL);
				customerUshopDO.setMainUuid("");
				customerUshopDao.save(customerUshopDO);

				//创建支付宝关系
				//AlipayUserInfoShareResponse userInfo = AliUntil.getUserInfo(accessToken,param);
				CustomerAliinfoRelDO ustomerAliinfoRelDO = new CustomerAliinfoRelDO();
				ustomerAliinfoRelDO.setCustomerId(customerUshopDO.getCustomerId());
				ustomerAliinfoRelDO.setIsDelete(CustomerAliinfoRelEnumConstants.ENUM_ISDELETE_UNDEL);
				ustomerAliinfoRelDO.setGmtCreate(new Date());
				ustomerAliinfoRelDO.setGmtModified(new Date());
				/*ustomerAliinfoRelDO.setAvatarUrl(userInfo.getAvatar());
				ustomerAliinfoRelDO.setCity(userInfo.getCity());
				ustomerAliinfoRelDO.setCountry(userInfo.getCountryCode());
				ustomerAliinfoRelDO.setGender(userInfo.getGender());
				ustomerAliinfoRelDO.setIsCertified(userInfo.getIsCertified());
				ustomerAliinfoRelDO.setIsStudentCertified(userInfo.getIsStudentCertified());
				ustomerAliinfoRelDO.setNickName(userInfo.getNickName());
				ustomerAliinfoRelDO.setProvince(userInfo.getProvince());
				ustomerAliinfoRelDO.setUserStatus(userInfo.getUserStatus());
				ustomerAliinfoRelDO.setUserType(userInfo.getUserType());*/
				ustomerAliinfoRelDO.setAlipayUserid(aliPayUserId);
				customerAliinfoRelDao.save(ustomerAliinfoRelDO);

			}else{
				logger.info("用户已存在");
				CustomerAliinfoRelDO customerAliinfoRelDO = customerAliinfoRelDOS.get(0);
				customerUshopDO = customerUshopDao.get(customerAliinfoRelDO.getCustomerId());
			}
				Map result = new HashMap();
				//授权
				UserToken userToken = new UserToken(customerUshopDO.getMobile(), customerUshopDO.getCustomerId(), "");//过期天数
				String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
				result.put("token", token);
				return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, result);

		}catch (AlipayApiException e){
			e.printStackTrace();

		}catch (Exception  ex){
			ex.printStackTrace();
		}
		return  ApiResult.failure("获取access_token失败");
	}

	@Override
	public String getAliUserIdByCustomerId(String customerId) {
		String aliUserId="";
		try {
			aliUserId = customerAliinfoRelDao.getAliUserIdByCustomerId(customerId);
		}catch (Exception e){
			e.printStackTrace();
		}
		return aliUserId;
	}


}
